/*
 * Copyright 2011 Francesco Lavra <francescolavra@interfree.it>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.droidtagger;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;

public class DroidTagger extends TabActivity {
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Resources res = getResources();
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Reusable TabSpec for each tab
        spec = tabHost.newTabSpec("tags")
        	   .setIndicator(res.getText(R.string.tags),
        			   		 res.getDrawable(R.drawable.ic_tab_tags))
        	   .setContent(R.id.tags);
        tabHost.addTab(spec);
        spec = tabHost.newTabSpec("browser")
 	   		   .setIndicator(res.getText(R.string.browser),
 	   				   		 res.getDrawable(R.drawable.ic_tab_browser))
 	   		   .setContent(R.id.browser);
        tabHost.addTab(spec);
        WebView browser = (WebView) findViewById(R.id.browser);
        browser.setWebViewClient(new WebViewClient());
        browser.getSettings().setJavaScriptEnabled(true);
    	EditText text = (EditText) findViewById(R.id.text);
    	text.setSingleLine(false);
    }
    public void TagURL(View view) {
    	EditText url = (EditText) findViewById(R.id.url);
    	RequestTags(WEB_SERVER_URL + "url=" + url.getText().toString());
    }
    public void BrowseURL(View view) {
    	EditText url = (EditText) findViewById(R.id.url);
    	WebView browser = (WebView) findViewById(R.id.browser);
    	String urlString = url.getText().toString();
    	if (!urlString.contains(":"))
    		urlString = "http://" + urlString;
    	browser.loadUrl(urlString);
    	getTabHost().setCurrentTabByTag("browser");
    }
    public void TagText(View view) {
    	EditText text = (EditText) findViewById(R.id.text);
    	String urlString = text.getText().toString().replace(" ", "%20");
    	urlString = urlString.replace("\n", "%0a");
    	urlString = WEB_SERVER_URL + "text=" + urlString;
    	RequestTags(urlString);
    }
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
    	getTabHost().setCurrentTabByTag("tags");
		WebView browser = (WebView) findViewById(R.id.browser);
    	RequestTags(WEB_SERVER_URL + "url=" + browser.getUrl());
    	return true;
    }
    public boolean loading;
    
    protected Dialog onCreateDialog(int id) {
    	if (id == LOADING) {
    		ProgressDialog progressDialog = new ProgressDialog(this);
    		progressDialog.setMessage(getResources().getText(R.string.loading));
    		progressDialog.setOnCancelListener(new CancelRequest(this));
    		return progressDialog;
    	}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	switch (id) {
    	case MALFORMED_URL:
			builder.setTitle(R.string.malformed_url);
			break;
    	case NETWORK_ERR:
			builder.setTitle(R.string.network_err);
			break;
    	case INVALID_RESP:
			builder.setTitle(R.string.invalid_resp);
			break;
     	}
		return builder.create();
   	}

    private void RequestTags(String url) {
    	loading = true;
    	showDialog(LOADING);
    	RequestThread requestThread = new RequestThread(url, handler);
    	requestThread.start();
    }
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
        	if (loading == false)
        		return;
        	loading = false;
    		dismissDialog(LOADING);
    		if (msg.arg1 != 0)
    			showDialog(msg.arg1);
    		TextView tags = (TextView) findViewById(R.id.tag_list);
    		String response = (String)msg.obj;
    		if (response.length() > 0)
    			tags.setText((String)msg.obj);
    		else
    			tags.setText(R.string.no_tags);
        }
    };
    private class CancelRequest implements DialogInterface.OnCancelListener {
    	public CancelRequest(DroidTagger activity) {
    		mActivity = activity;
    	}
		@Override
		public void onCancel(DialogInterface arg0) {
			mActivity.loading = false;			
		}
		private DroidTagger mActivity;
    }
    private class RequestThread extends Thread {
    	public RequestThread(String url, Handler handler) {
    		mUrl = url;
    		mHandler = handler;
    	}
    	public void run() {
            String response = "";
            Message msg = mHandler.obtainMessage();
            msg.arg1 = 0;
    		try {
                HttpURLConnection conn = (HttpURLConnection) new URL(mUrl).openConnection();
                XmlPullParser parser = Xml.newPullParser();
                parser.setInput(conn.getInputStream(), null);
                int eventType = parser.nextTag();
                while (eventType != XmlPullParser.START_TAG ||
                		parser.getName() != "meme")
                	eventType = parser.nextTag();
                eventType = parser.nextTag();
                while (eventType != XmlPullParser.END_TAG &&
                		parser.getName() != "meme") {
                	if (eventType == XmlPullParser.START_TAG &&
                		parser.getName() == "dim") {
                		if (parser.getAttributeValue(null, "type").equals("messages"))
                			// Some kind of error occurred, most likely the
                			// supplied URL was invalid. Don't display anything
                			// in the tag list.
                			break;
                		response += "\n" + parser.getAttributeValue(null, "type") + ":\n";
                		eventType = parser.nextTag();
                		while (eventType == XmlPullParser.START_TAG &&
                				parser.getName() == "item") {
                			response += parser.nextText() + " ";
                			parser.nextTag();
                			parser.nextTag();
                		}
                		response += "\n";
                	}
                	parser.nextTag();
                }
    		} catch (MalformedURLException e) {
    			msg.arg1 = MALFORMED_URL;
    		} catch (IOException e) {
    			msg.arg1 = NETWORK_ERR;
    		} catch (XmlPullParserException e) {
    			msg.arg1 = INVALID_RESP;
    		}
            msg.obj = response;
    		mHandler.sendMessage(msg);
    	}
    	
    	private String mUrl;
    	private Handler mHandler;
    }
    private static final String WEB_SERVER_URL = "http://tagthe.net/api/?";
    private static final int MALFORMED_URL = 1;
    private static final int NETWORK_ERR = 2;
    private static final int INVALID_RESP = 3;
    private static final int LOADING = 4;
}